package lab2rsagroup10;

import java.math.BigInteger;
import java.util.Arrays;
import java.util.Iterator;

public class CipherTable implements Iterable<CipherTable.Entry>,
			Iterator<CipherTable.Entry> {
	
	private int next_entry_;
	private int iterator_;
	private final Entry[] entries_;
	
	public static class Entry implements Comparable<Entry> {
		private Entry(final BigInteger i, final BigInteger e, final BigInteger inv) {
			index = i;
			entry = e;
			inverseEntry = inv;
		}
		
		public final BigInteger index;
		public final BigInteger entry;
		public final BigInteger inverseEntry;
		
		@Override
		public int compareTo(Entry o) {
			return this.entry.compareTo(o.entry);
		}
	}
	
	public CipherTable(final int size) {
		next_entry_ = 0;
		entries_ = new Entry[size];
	}
	
	public Entry lookUpEntry(final BigInteger entry) {
		int i = Arrays.binarySearch(entries_, 
				new CipherTable.Entry(null, entry, null));
		if (i >= 0) {
			return entries_[i];
		}
		
		return null;
	}
	
	public void addEntry(final BigInteger entry, final BigInteger revEntry) {
		assert next_entry_ < entries_.length;
		int i = next_entry_++;
		CipherTable.Entry e = new CipherTable.Entry(BigInteger.valueOf(next_entry_), 
				entry, revEntry);
		entries_[i] = e;
	}
	
	public void sortEntries() {
		Arrays.sort(entries_);
	}
	
	@Override
	public Iterator<Entry> iterator() {
		iterator_ = 0;
		return this;
	}

	@Override
	public boolean hasNext() {
		if(iterator_ < entries_.length) {
			return true;
		}
		return false;
	}

	@Override
	public Entry next() {
		return entries_[iterator_++];
	}

	@Override
	public void remove() {
		throw new UnsupportedOperationException();
	}
}
